package com.guomao.IODemo;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileExample {
    public static void main(String[] args) {
        String randomFile = "random.dat";

        // 写入数据
        try (RandomAccessFile raf = new RandomAccessFile(randomFile, "rw")) {
            raf.writeInt(100);
            raf.writeDouble(3.14159);
            raf.writeUTF("Hello, Random Access File!");
            System.out.println("随机访问文件写入完成！");
        } catch (IOException e) {
            System.err.println("写入随机访问文件时出错: " + e.getMessage());
        }

        // 随机读取数据
        try (RandomAccessFile raf = new RandomAccessFile(randomFile, "r")) {
            raf.seek(0); // 移动到文件开头
            int num = raf.readInt();
            double pi = raf.readDouble();
            raf.seek(8 + 8); // 跳过整数和双精度浮点数，移动到字符串位置
            String message = raf.readUTF();
            System.out.println("随机读取的数据：");
            System.out.println("整数: " + num);
            System.out.println("双精度浮点数: " + pi);
            System.out.println("字符串: " + message);
        } catch (IOException e) {
            System.err.println("读取随机访问文件时出错: " + e.getMessage());
        }
    }
}